/*
 * @Author: 肖思汗 
 * @Date: 2025-06-25 09:26:35 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-07-16 09:37:44
 */


import clsx from "clsx";
import { observer } from "mobx-react-lite";
import { ReactNode, useRef, useState } from "react";
import styles from "./layerList.module.less";
import layerListStore from "./layerListStore";
import { Button, Popup } from "@nutui/nutui-react-taro";
import MyScrollView from "src/components/MyScrollView/MyScrollView";
import { View, MovableArea, MovableView } from '@tarojs/components'
import Taro from "@tarojs/taro";
import { cloneDeep, isEqual } from "lodash";
import leftTopStore from "../LeftTop/leftTopStore";
import MyPopup from "src/components/MyPopup/MyPopup";



interface Iprops {
    children?: ReactNode
}

// 层级编辑
const LayerList = observer(() => {

    const [list, setList] = useState([
        { id: 0, text: 'Item 0', y: 0 },
        { id: 1, text: 'Item 1', y: 50 },
        { id: 2, text: 'Item 2', y: 100 },
        { id: 3, text: 'Item 3', y: 150 },
        { id: 4, text: 'Item 4', y: 200 },
        { id: 5, text: 'Item 5', y: 250 },
        // ...更多初始数据
    ])
    const [activeId, setActiveId] = useState(null);
    const currentIndex = useRef(0);
    const currentY = useRef(0);
    const ids = useRef(list.map(item => item.id));


    // 处理拖拽开始
    const handleTouchStart = (index) => {
        currentIndex.current = index;
        // setActiveId(id)
        // Taro.vibrateShort() // 触觉反馈^5^
    }

    // 动态计算新位置并重新排序
    const handleTouchMove = (e, currentIndex) => {
        const movedY = e.mpEvent.detail.y;
        currentY.current = movedY;
        console.log("movedY", movedY);
        // const newList = list.map((item, index) => {
        //     if (index === currentIndex) return item
        //     // 自动挤压逻辑：根据移动距离判断是否需要交换位置^2^^4^
        //     const shouldSwap = movedY > item.y + 50 / 2 || movedY / 2 < item.y - 50;
        //     return shouldSwap ? { ...item, y: item.y + (movedY > item.y ? -50 : 50) } : item
        // })
        // setList(newList)

        // 更新当前元素的位置
        // const updatedList = list.map((item, index) => {
        //     if (index === currentIndex) return { ...item, y: movedY };
        //     return item;
        // });
        // setList(updatedList);

        // list[0].y = 50;
        // list[1].y = 0;

        // if (movedY > 50) {
        //     list[1].y = 0;
        // } else {
        //     list[0].y = 50;
        // }
        // setList(cloneDeep(list));

        // 计算目标索引
        list[currentIndex].y = currentY.current;
        const targetIndex = Math.round(currentY.current / 50);

        // 如果位置则重新计算每个元素的位置
        if (currentIndex !== targetIndex) {
            const newList = [];
        }


        // console.log("targetIndex", targetIndex);
        // const arrayY = list.map(l => l.y).sort((a, b) => a - b);

        // const newList = list.sort((a, b) => a.y - b.y);
        // newList.map((item, index) => {
        //     if (index === currentIndex) {
        //         item.y = currentY.current;
        //     } else {
        //         item.y = (index * 50);
        //     }
        // });

        // if (!isEqual(ids.current, newList.map(l => l.id))) {
        //     console.log("-------------setList-------------");
        //     ids.current = newList.map(l => l.id);
        //     setList(cloneDeep(newList));
        // }

    }

    // 拖拽结束后的最终排序
    const handleTouchEnd = () => {
        // setList(prev => [...prev].sort((a, b) => a.y - b.y).map((item, i) => ({
        //     ...item,
        //     y: i * itemHeight.current // 重置为规整坐标^1^
        // })))
        // setActiveId(null)

        // if (movedY > 50) {
        //     list[1].y = 0;
        // } else {
        //     list[1].y = 50;
        // }

        // list[currentIndex.current].y = currentY.current;

        // const newList = list.sort((a, b) => a.y - b.y);
        // newList.map((item, index) => {
        //     item.y = (index * 50) + Math.random();
        // });
        // if (!isEqual(ids.current, newList.map(l => l.id))) {
        // ids.current, newList.map(l => l.id);
        // setList(cloneDeep(newList));
        // }
    }

    const m = () => {

        list[0].y = 0;
        list[1].y = 50;
        setList(cloneDeep(list));
    }

    return (
        <MyPopup
            open={!leftTopStore.showColorPicker && layerListStore.show}
            className={styles.layerList}
            closeable
            title="图层"
            onClose={() => {
                layerListStore.setShow(false);
            }}
        >
            {/* <Button
                type="primary"
                size="mini"
                onClick={m}
            >排序</Button> */}

            <MyScrollView
                style={{
                    height: "320rpx",
                    width: "710rpx",
                    backgroundColor: '#eeeeee'
                }}
            >
                <MovableArea
                    className={styles.dragBox}
                    style={{
                        backgroundColor: '#dddddd'
                    }}>
                    {list.map((item, index) => (
                        <MovableView
                            animation={true}
                            key={index}
                            direction="all"
                            y={item.y}
                            onChange={(e) => handleTouchMove(e, index)}
                            onTouchEnd={handleTouchEnd}
                            onTouchStart={() => handleTouchStart(index)}
                            style={{
                                height: "100rpx",
                                width: '100rpx',
                                zIndex: activeId === item.id ? 99 : 1,
                                border: "2rpx solid #cccccc",
                                boxSizing: "border-box"
                            }}
                        >
                            {item.text}
                        </MovableView>
                    ))}
                </MovableArea>
            </MyScrollView>
        </MyPopup>
    );
});

export default LayerList;